module.exports = class extends think.Controller {
	constructor(ctx) {
		super(ctx);
		this.rule = this.model("system/rule");
		this.conf = this.model("weixin/config");
		this.db = this.model(ctx.controller);

	}

	async __before() {
		let config = think.config();
		this.assign("config", config);

		let rule = await this.rule.where({
			url: ['like', '/' + this.ctx.controller + '/' + this.ctx.action]
		}).order("url desc").find();

		if(think.isEmpty(rule)) {

			return this.ctx.throw(404);
		}

		if(rule.auth == 1) {
			let auth = await this.session("auth");
			let user = await this.session("user") || {};
			if(auth && user.status == 1) {
				console.log(rule)

				let permission = rule.code;

				let permissions = await this.session("permission") || [];
				if(permissions.indexOf(permission) > -1) {

					let user = await this.session("user");
					let firstMenus = await this.session("firstMenus");
					let secondMenus = await this.session("secondMenus");
					let customMenus = await this.session("customMenus");
					let menuRoot = await this.rule.where({
						code: rule.code.split(":")[0]
					}).find();

					this.assign("user", user);
					this.assign("firstMenus", firstMenus);
					this.assign("secondMenus", secondMenus);
					this.assign("customMenus", customMenus);
					this.assign("menuCode", rule.code);
					this.assign("menuRoot", menuRoot.id);

				} else {

					return this.ctx.throw(403);
				}

			} else {
				return this.redirect("/system/user/login");
			}

		}
	}

	async deleteAction() {

		let ids = this.post("id") || JSON.parse(this.post("ids"));

		let rows = await this.db.where({
			id: ['IN', ids]
		}).delete();
		if(rows == 0) {
			return this.fail("删除失败")
		}
		return this.success("删除成功")

	}

};